package com.lf.web.service.login;

import com.lf.data.Global;
import com.lf.data.search.Query;
import com.lf.web.service.ResponseCode;
import com.lf.web.service.ResponseInfo;
import com.lf.web.service.ServiceSupport;
import com.lf.web.service.system.user.User;
import com.lf.web.service.system.user.UserDAO;
import org.apache.log4j.Logger;

import java.util.Map;

public class LoginService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(LoginService.class);
    private UserDAO userDAO;

    private String act = "";
    private Login login = new Login();

    private Map<String, Object> session;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public String execute() {
        act = form.getString("act");
        this.session = context.getSession();
        if ("in".equals(act)) {
            return auth();
        } else if ("out".equals(act)) {
            return out();
        } else {
            return "login";
        }
    }

    public String out() {
        session.remove("user");
        return "logout";
    }

    private String auth() {
        boolean result = form.getCluster(login);
        LOGGER.debug("登录信息：" + login + ",sessionCode=" + session.get(Global.SESSION_CAPTCHA));
        ResponseInfo rj = new ResponseInfo();
        Object vCode = session.get(Global.SESSION_CAPTCHA);
        if (result) {
            if (vCode == null || !vCode.toString().equalsIgnoreCase(login.getString(Login.CAPTCHA))) {
                rj.setCode(ResponseCode.ERROR_CAPTCHA);
                session.remove(Global.SESSION_CAPTCHA);
            } else {
                Query query = new Query();
                query.eq(User.USER_NAME, login.get(Login.USER_NAME));
                query.eq(User.PASSWORD, login.get(Login.PASSWORD));
                User user = new User(userDAO.findOne(query));
                if (user.isEmpty()) {
                    rj.setCode(ResponseCode.ERROR_USERNAME_OR_PASSWORD);
                } else {
                    session.put(Global.SESSION_USER, user);
                    session.remove(Global.SESSION_CAPTCHA);
                    rj.setCode(ResponseCode.SUCCESS);
                }
            }
            out(rj);
        } else {
            LOGGER.error("非法登录：" + login);
        }
        return NONE;
    }
}
